package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.domain.entities.Cheque;
import com.jsh.erp.domain.entities.UserBusiness;
import com.jsh.erp.domain.param.ChequeReportParam;
import com.jsh.erp.domain.vo.ChequeReport;
import com.jsh.erp.service.cheque.ChequeService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.ErpInfo;
import com.jsh.erp.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;

@RestController
@RequestMapping(value = "/cheque")
@Api(tags = {"支票管理"})
public class ChequeController {

    private Logger logger = LoggerFactory.getLogger(ChequeController.class);


    @Resource
    private ChequeService chequeService;
    @Resource
    private UserBusinessService userBusinessService;

    /**
     * 支票列表
     */
    @GetMapping(value = "/getList")
    @ApiOperation(value = "支票列表")
    public BaseResponseInfo getAllList(@RequestParam(required = false) String chequeNumber) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            List<Cheque> cheques = chequeService.getList(chequeNumber);
            res.code = 200;
            res.data = cheques;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }


    /**
     * 支票报表
     * 出库单号，客户，商品信息，销售员，订单金额，发货日期，签收日期。
     */
    @GetMapping(value = "/report")
    @ApiOperation(value = "支票报表")
    public String chequeReport(ChequeReportParam param) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<>();
        try {
            List<ChequeReport> cheques = chequeService.getReport(param);
            Long l = chequeService.countReport(param);
            map.put("rows", cheques);
            map.put("total", l == null ? 0L : l);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            res.code = 500;
            res.data = "获取数据失败";
        }
        return returnJson(map, ErpInfo.OK.name, ErpInfo.OK.code);
    }


    @GetMapping(value = "/bankName/list")
    @ApiOperation(value = "收款银行列表")
    public String chequeBankNameList() throws Exception {
        Map<String, Object> objectMap = new HashMap<String, Object>();

        try {
            List<UserBusiness> chequeBankName = userBusinessService.getBasicData("1", "chequeBankName");
            if (chequeBankName != null && chequeBankName.size() > 0) {
                String bankStr = chequeBankName.get(0).getValue();
                if (StringUtil.isNotEmpty(bankStr)) {
                    List<String> result = parseStringToList(bankStr);
                    objectMap.put("total", result.size());
                    objectMap.put("rows", result);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            objectMap.put("rows", new ArrayList<Object>());
            return returnJson(objectMap, "no data", ErpInfo.OK.code);

        }
        return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
    }

    @PostMapping(value = "/bankName/add")
    @ApiOperation(value = "添加收款银行")
    public String addChequeBankName(@RequestBody Map<String, String> requestMap, HttpServletRequest request) throws Exception {
        String name = requestMap.get("name");
        if (StringUtils.isEmpty(name)) {
            return returnJson(null, ErpInfo.BAD_REQUEST.name, ErpInfo.BAD_REQUEST.code);
        }
        Map<String, Object> objectMap = new HashMap<String, Object>();
        try {
            List<UserBusiness> chequeBankName = userBusinessService.getBasicData("1", "chequeBankName");
            if (chequeBankName != null && chequeBankName.size() > 0) {
                String bankStr = chequeBankName.get(0).getValue();
                bankStr = bankStr + "[" + name + "]";
                JSONObject ubObj = new JSONObject();
                ubObj.put("id", chequeBankName.get(0).getId());
                ubObj.put("type", chequeBankName.get(0).getType());
                ubObj.put("keyId", chequeBankName.get(0).getKeyId());
                ubObj.put("value", bankStr);
                userBusinessService.updateUserBusiness(ubObj, request);
            } else {
                String bankStr = "";
                bankStr = bankStr + "[" + name + "]";
                JSONObject ubObj = new JSONObject();
                ubObj.put("type", "chequeBankName");
                ubObj.put("keyId", "1");
                ubObj.put("value", bankStr);
                userBusinessService.insertUserBusiness(ubObj, request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return returnJson(null, ErpInfo.BAD_REQUEST.name, ErpInfo.BAD_REQUEST.code);

        }
        return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
    }

    @PostMapping(value = "/bankName/delete")
    @ApiOperation(value = "删除收款银行")
    public String deleteChequeBankName(@RequestBody Map<String, String> requestMap, HttpServletRequest request) throws Exception {
        String name = requestMap.get("name");
        if (StringUtils.isEmpty(name)) {
            return returnJson(null, ErpInfo.BAD_REQUEST.name, ErpInfo.BAD_REQUEST.code);
        }
        Map<String, Object> objectMap = new HashMap<String, Object>();
        try {
            List<UserBusiness> chequeBankName = userBusinessService.getBasicData("1", "chequeBankName");
            if (chequeBankName != null && chequeBankName.size() > 0) {
                String bankStr = chequeBankName.get(0).getValue();
                bankStr = bankStr.replace("[" + name + "]", "");
                JSONObject ubObj = new JSONObject();
                ubObj.put("id", chequeBankName.get(0).getId());
                ubObj.put("type", chequeBankName.get(0).getType());
                ubObj.put("keyId", chequeBankName.get(0).getKeyId());
                ubObj.put("value", bankStr);
                userBusinessService.updateUserBusiness(ubObj, request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return returnJson(null, ErpInfo.BAD_REQUEST.name, ErpInfo.BAD_REQUEST.code);

        }
        return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
    }


    @GetMapping(value = "/payeeName/list")
    @ApiOperation(value = "收款银行列表")
    public String payeeNameList() throws Exception {
        Map<String, Object> objectMap = new HashMap<String, Object>();

        try {
            List<UserBusiness> chequeBankName = userBusinessService.getBasicData("1", "payeeName");
            if (chequeBankName != null && chequeBankName.size() > 0) {
                String bankStr = chequeBankName.get(0).getValue();
                if (StringUtil.isNotEmpty(bankStr)) {
                    List<String> result = parseStringToList(bankStr);
                    objectMap.put("total", result.size());
                    objectMap.put("rows", result);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            objectMap.put("rows", new ArrayList<Object>());
            return returnJson(objectMap, "no data", ErpInfo.OK.code);

        }
        return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
    }

    @PostMapping(value = "/payeeName/add")
    @ApiOperation(value = "添加收款人")
    public String addPayeeName(@RequestBody Map<String, String> requestMap, HttpServletRequest request) throws Exception {
        String name = requestMap.get("name");
        if (StringUtils.isEmpty(name)) {
            return returnJson(null, ErpInfo.BAD_REQUEST.name, ErpInfo.BAD_REQUEST.code);
        }
        Map<String, Object> objectMap = new HashMap<String, Object>();
        try {
            List<UserBusiness> chequeBankName = userBusinessService.getBasicData("1", "payeeName");
            if (chequeBankName != null && chequeBankName.size() > 0) {
                String bankStr = chequeBankName.get(0).getValue();
                bankStr = bankStr + "[" + name + "]";
                JSONObject ubObj = new JSONObject();
                ubObj.put("id", chequeBankName.get(0).getId());
                ubObj.put("type", chequeBankName.get(0).getType());
                ubObj.put("keyId", chequeBankName.get(0).getKeyId());
                ubObj.put("value", bankStr);
                userBusinessService.updateUserBusiness(ubObj, request);
            } else {
                String bankStr = "";
                bankStr = bankStr + "[" + name + "]";
                JSONObject ubObj = new JSONObject();
                ubObj.put("type", "payeeName");
                ubObj.put("keyId", "1");
                ubObj.put("value", bankStr);
                userBusinessService.insertUserBusiness(ubObj, request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return returnJson(null, ErpInfo.BAD_REQUEST.name, ErpInfo.BAD_REQUEST.code);

        }
        return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
    }

    @PostMapping(value = "/payeeName/delete")
    @ApiOperation(value = "删除收款人")
    public String deletePayeeName(@RequestBody Map<String, String> requestMap, HttpServletRequest request) throws Exception {
        String name = requestMap.get("name");
        if (StringUtils.isEmpty(name)) {
            return returnJson(null, ErpInfo.BAD_REQUEST.name, ErpInfo.BAD_REQUEST.code);
        }
        Map<String, Object> objectMap = new HashMap<String, Object>();
        try {
            List<UserBusiness> chequeBankName = userBusinessService.getBasicData("1", "payeeName");
            if (chequeBankName != null && chequeBankName.size() > 0) {
                String bankStr = chequeBankName.get(0).getValue();
                bankStr = bankStr.replace("[" + name + "]", "");
                JSONObject ubObj = new JSONObject();
                ubObj.put("id", chequeBankName.get(0).getId());
                ubObj.put("type", chequeBankName.get(0).getType());
                ubObj.put("keyId", chequeBankName.get(0).getKeyId());
                ubObj.put("value", bankStr);
                userBusinessService.updateUserBusiness(ubObj, request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return returnJson(null, ErpInfo.BAD_REQUEST.name, ErpInfo.BAD_REQUEST.code);

        }
        return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
    }


    public static List<String> parseStringToList(String input) {
        List<String> list = new ArrayList<>();
        // 使用正则表达式匹配 [任意内容]
        Pattern pattern = Pattern.compile("\\[(.*?)\\]");
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            // 将匹配到的内容添加到列表中
            list.add(matcher.group(1)); // group(1) 是括号内的内容
        }
        return list;
    }

    /**
     * 批量设置状态-审核/反审核
     */
    @PostMapping(value = "/batchSetStatus")
    @ApiOperation(value = "批量设置状态")
    public String batchSetStatus(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request) throws Exception {
        Integer status = jsonObject.getInteger("status");
        String ids = jsonObject.getString("ids");
        Map<String, Object> objectMap = new HashMap<>();
        int res = chequeService.batchSetStatus(status, ids);
        if (res > 0) {
            return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
        }
    }

}
